import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { LoveMakeupCouponService } from '../services/love-makeup-coupon.service';

@Component({
  selector: 'app-love-makeup-coupon-edit',
  templateUrl: './love-makeup-coupon-edit.component.html',
  styleUrls: ['./love-makeup-coupon-edit.component.scss'],
  providers: [DatePipe]
})
export class LoveMakeupCouponEditComponent implements OnInit {

  routeParams: any = {};
  formParams: any = {
    status: 5,
    type: 2, // 加价券类型 1：满加 2：百分比
    name: '', // 前端名称
    remark: '', // 备注
    total: '', // 总数量
    orderLimitMoney: '', // 门槛（满多少）
    limitSmall: '', // 加价值
    limitBig: '', // 最高加价金额

    userType: 0, // 适用用户 0：不限制 1：C端 2：B端
    isShowWeb: 1, // 前端展示 0：不展示 1：展示
    getBeginTime: '', // 可领取开始时间
    getEndTime: '', // 可领取结束时间
    
    limitTimeNum: 0, // 限制使用 xx天 0：当天 1：明天
    useBeginTime: '', // 限制使用开始时间
    useEndTime: '', // 限制使用结束时间
    useDesc: '', // 使用说明

    applyColour: '', // 适用成色 0：全部 1：二手 2：准新
    containsModel: '', // 机型list 0：为全部 -1：为全不选

    remind: '0', // 过期N天提醒(参考优惠券、暂无用、用作提交)
    userLimitNum: '1', // 没人限领次数(参考优惠券、暂无用、用作提交)
    autoReverse: '0' // 每N天首次进店自动发放(参考优惠券、暂无用、用作提交)
  };

  // 可领取时间
  receiveDates: any[] = [];

  // 适用用户
  userTypeOptions: any = [
    {value: 0, label: '不限制'},
    {value: 1, label: 'C端'},
    {value: 2, label: 'B端'}
  ];

  // 有效时间
  effectiveDates: any[] = [];
  effectiveType: number = 1;

  // 适用成色
  conditionOptions: any = [
    {value: 0, label: '全部'},
    {value: 1, label: '二手机'},
    {value: 2, label: '准新机'}
  ];

  // 适用机型
  isModelVisible = false;
  defaultModelKeys: any = [];
  modelAll: boolean = false;

  // loading
  sumitLoading: boolean = false;
  releaseLoading: boolean = false;

  // 规则说明默认值(格式)
  defaultTuleText: string = '1.有效时间：xxxx.xx.xx 00:00-xxxx.xx.xx 23:59；\n2.订单至少有一台机器实际验机价≥50元方可享受加价；\n3.每个订单只有一台机器可以享受加价，当同一个订单存在多台机器时，则以验机价最高的那台机器来计算加价金额，加价金额=该台机器验机价*5%，封顶200元；\n4.加价券仅限二手手机回收使用，准新机不参与；\n5.若您参与活动，视为同意所有规则，活动最终解释权归爱思商城所有,如有疑问请咨询爱思商城客服。';

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private services: LoveMakeupCouponService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    // 新增默认规则说明格式
    if (['0'].includes(this.routeParams.type)) {
      this.formParams.useDesc = this.defaultTuleText;
    }

    if (['1', '3'].includes(this.routeParams.type)) {
      this.loadDetailData();
    }
  }

  // load datails
  async loadDetailData() {
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getCouponUpdateDetail(this.routeParams.id);
    this.message.remove(messId);
    
    if (code === 0) {
      this.formParams.status = data.status;
      this.formParams.type = data.type; // 加价券类型 1：满加 2：百分比
      this.formParams.name = data.name; // 前端名称
      this.formParams.remark = data.remark || ''; // 备注
      this.formParams.total = data.total; // 总数量
      this.formParams.orderLimitMoney = data.orderLimitMoney; // 门槛（满多少）
      this.formParams.limitSmall = data.limitSmall; // 加价值
      this.formParams.limitBig = data.limitBig; // 最高加价金额

      this.formParams.userType = data.userType; // 适用用户 0：不限制 1：C端 2：B端
      this.formParams.isShowWeb = data.isShowWeb; // 前端展示 0：不展示 1：展示
      this.formParams.getBeginTime = this.formParams.isShowWeb == 1 ? data.getBeginTime : ''; // 可领取开始时间
      this.formParams.getEndTime = this.formParams.isShowWeb == 1 ? data.getEndTime : ''; // 可领取结束时间
      this.receiveDates = this.formParams.isShowWeb == 1 ? [data.getBeginTime, data.getEndTime] : []; // 可领取dates

      this.effectiveType = data.limitTimeNum == '-1' ? 2 : 1;
      this.formParams.limitTimeNum = data.limitTimeNum == '-1' ? '0' : data.limitTimeNum; // 限制使用 xx天 0：当天 1：明天
      this.formParams.useBeginTime = this.effectiveType === 1 ? '' : data.useBeginTime; // 限制使用开始时间
      this.formParams.useEndTime = this.effectiveType === 1 ? '' : data.useEndTime; // 限制使用结束时间
      this.effectiveDates = this.effectiveType === 2 ? [data.useBeginTime, data.useEndTime] : [];
      this.formParams.useDesc = data.useDesc || ''; // 使用说明

      this.formParams.applyColour = data.applyColour; // 适用成色
      this.formParams.containsModel = data.containsModel; // 机型
      this.modelAll = data.containsModel == '0' ? true : false;
      this.defaultModelKeys = data.containsModel != '0' ? data.containsModel.split(',') : [];
    }
  }

  /**
   * ----------------------------------------------------------------
   * 指定机型 Modal Select Tree
   * ----------------------------------------------------------------
   */
  selectMoreModel() {
    this.defaultModelKeys = [];
    this.defaultModelKeys = this.mergeTreeKey();
    this.isModelVisible = true;
  }

  subModelTree(objs: any) {
    // this.formParams.containsTypes = objs.brandList.join(',');
    // this.formParams.containsSeries = objs.seriesList.join(',');
    this.formParams.containsModel = objs.modelList.join(',');
    this.defaultModelKeys = this.mergeTreeKey();
    if (this.defaultModelKeys.length) {
      this.modelAll = false;
    }
  }

  mergeTreeKey() {
    // let brandArr = this.formParams.containsTypes ? this.formParams.containsTypes.split(',') : [];
    // let seriesArr = this.formParams.containsSeries ? this.formParams.containsSeries.split(',') : [];
    let modelArr = (this.formParams.containsModel && this.formParams.containsModel != '0') ? this.formParams.containsModel.split(',') : [];
    return [...modelArr].map((item: any) => +item);
  }

  modelOwnerAllChange(val: any) {
    this.formParams.containsModel = '';
    this.defaultModelKeys = [];
  }

  /**
   * ----------------------------------------------------------------
   * 验证
   * ----------------------------------------------------------------
   */
  isVerifForms() {
    if (this.isEmpty(this.formParams.name)) {
      this.message.warning('请输入前端名称');
      return false;
    } else if (this.isEmpty(this.formParams.total)) {
      this.message.warning('请输入总数量');
      return false;
    } else if (this.isEmpty(this.formParams.orderLimitMoney) || this.isEmpty(this.formParams.limitSmall)) {
      this.message.warning('请输入加价条件');
      return false;
    } else if (this.formParams.type === 2 && this.isEmpty(this.formParams.limitBig)) {
      this.message.warning('请输入最高加价金额');
      return false;
    } else if (!this.receiveDates.length && this.formParams.isShowWeb === 1) {
      this.message.warning('请选择可领取时间');
      return false;
    } else if (this.effectiveType === 1 && this.isEmpty(this.formParams.limitTimeNum)) {
      this.message.warning('请输入有效期');
      return false;
    } else if (this.effectiveType === 2 && !this.effectiveDates.length) {
      this.message.warning('请选择有效期');
      return false;
    } else if (this.isEmpty(this.formParams.useDesc)) {
      this.message.warning('请输入规则说明');
      return false;
    } else if (this.formParams.useDesc === this.defaultTuleText) {
      this.message.warning('当前规则说明为默认提示、请编辑规则说明');
      return false;
    } else if (this.isEmpty(this.formParams.applyColour)) {
      this.message.warning('请选择适用成色');
      return false;
    } else if (!this.modelAll && !this.defaultModelKeys.length) {
      this.message.warning('请选择适用机型');
      return false;
    } else {
      return true;
    }
  }

  /**
   * ----------------------------------------------------------------
   * 保存 | 发布
   * ----------------------------------------------------------------
   */
  async submitForms(status?: number) {
    if (!this.isVerifForms()) {
      return
    }
    let params = {
      ...this.formParams,
      limitBig: this.isEmpty(this.formParams.limitBig) ? '0' : this.formParams.limitBig,
      limitTimeNum: this.effectiveType === 2 ? '-1' : this.formParams.limitTimeNum,
      containsModel: this.paramHandle(this.modelAll, this.defaultModelKeys)
    }
    
    status ? (this.releaseLoading = true) : (this.sumitLoading = true);
    let res: any;
    if (['0', '3'].includes(this.routeParams.type)) {
      params.status = 5;
      // 发布
      if (status) {
        params.status = status;
      }
      res = await this.services.addCouponData(params);
    } else {
      // 发布
      if (status) {
        params.status = status;
      }
      res = await this.services.editCouponData(params, this.routeParams.id);
    }
    this.sumitLoading = false;
    this.releaseLoading = false;
    
    if (res.code === 0) {
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  // params handle 0：为全部 -1：为全不选
  paramHandle(state: boolean, result: any) {
    let tempStr = '';
    if (state) {
      tempStr = '0';
    } else if (!state && !result.length) {
      tempStr = '-1';
    } else {
      if (Object.prototype.toString.call(result) === '[object Array]') {
        tempStr = result.join(',');
      } else {
        tempStr = result;
      }
    }
    return tempStr;
  }

  /**
   * 发布
   */
  releaseCoupon() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认发布?',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        // let params = {
        //   id: this.routeParams.id,
        //   status: 1
        // }
        // this.releaseLoading = true;
        // const {code, message}: any = await this.services.examineCouponItem(params);
        // this.releaseLoading = false;

        // if (code === 0) {
        //   this.message.success('发布成功');
        //   this.back();
        // } else {
        //   this.message.error(message);
        // }
        this.submitForms(1);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * Other
   * ----------------------------------------------------------------
   */
  couponTypeChange(val: number) {
    this.formParams.limitBig = '';
  }

  onDateChange(result: any[], kes: string[]) {
    this.formParams[kes[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[kes[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  // 有效期 Change
  effectiveChange(val: any) {
    this.formParams.limitTimeNum = 0;
    this.formParams.useBeginTime = '';
    this.formParams.useEndTime = '';
    this.effectiveDates = [];
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // back
  back() {
    history.back();
  }

  // 禁止操作
  setDisabled(special?: string) {
    // 草稿全部可编辑
    if (this.formParams.status === 5 || ['0', '3'].includes(this.routeParams.type)) {
      return false;
    }

    // 已发布部分编辑 status [1, 2]
    if ([1, 2].includes(this.formParams.status) && special) {
      return false;
    }

    return true;
  }

  // 前端展示
  isShowChange(val: any) {
    if (val == 0) {
      this.formParams.getBeginTime = '';
      this.formParams.getEndTime = '';
      this.receiveDates = [];
    }
  }
}
